<template>
  <page-header-wrapper>
    <a-card :bordered='false'>
      <div class='table-page-search-wrapper'>
        <a-form layout='inline'>
          <a-row :gutter='48'>
            <a-col :md='8' :sm='24'>
              <a-form-item label='设备编号'>
                <a-input v-model='queryParam.equipmentNo' placeholder='' />
              </a-form-item>
            </a-col>
            <a-col :md='8' :sm='24'>
              <a-form-item label='设备型号'>
                <a-select v-model='queryParam.alarmsType'>
                  <a-select-option value='光伏'>
                    光伏
                  </a-select-option>
                  <a-select-option value='摄像头'>
                    摄像头
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md='!advanced && 8 || 24' :sm='24'>
              <a-button type='primary' @click='$refs.table.refresh(true)'>查询</a-button>
              <a-button style='margin-left: 8px' @click='() => {this.queryParam = {alarmsType: "光伏"};$refs.table.refresh(true)}'>重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class='table-operator'>
        <a-button type='primary' icon='plus' @click='handleAdd'>新建</a-button>
        <a-divider type='vertical' />
        <a-button type='primary' icon='plus' @click='handleAddVersion'>固件更新</a-button>
      </div>

      <s-table
        ref='table'
        size='default'
        rowKey='key'
        :columns='columns'
        :data='loadData'
        :alert='true'
        :rowSelection='rowSelection'
        showPagination='auto'
      >
        <span slot='serial' slot-scope='text, record, index'>
          {{ index + 1 }}
        </span>
        <span slot='no' slot-scope='text'>
          <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
        </span>
        <span slot='deviceName' slot-scope='text'>
          <ellipsis :length='10' tooltip>{{ text }}</ellipsis>
        </span>
        <span slot='status' slot-scope='text'>
          <!-- <a-badge :status="text" /> -->
          <ellipsis :length='4' tooltip>{{ text }}</ellipsis>
        </span>

        <span slot='action' slot-scope='text, record'>
          <template>
            <a @click='handleEdit(record)'>编辑</a>
            <a-divider type='vertical' />
            <a @click='handleDeleteOk(record.id)'>删除</a>
            <a-divider type='vertical' />
            <a @click='handleDSettingOk(record)'>设置</a>
            <a-divider type='vertical' />
            <a @click='handleDetail(record)'>详情</a>
            <!-- <a @click="handleEdit(record)">配置</a>
            <a @click="handleSub(record)">订阅报警</a> -->
          </template>
        </span>
      </s-table>

      <create-form-devicelist
        ref='createModal'
        :visible='visible'
        :loading='confirmLoading'
        :model='mdl'
        :cityValue='cityValue'
        @areaChange='areaChange'
        @cancel='handleCancel'
        @ok='handleOk'
      />
      <create-item
        ref='createItem'
        :title='devicetitle'
        :visible='visible2'
        :loading='confirmLoading2'
        :model='mdl2'
        @cancel='handleCancel2'
        @ok='handleOk2'
      />
      <create-item2
        ref='createItem2'
        title='固件更新'
        :visible='visible3'
        :loading='confirmLoading3'
        :model='mdl3'
        @cancel='handleCancel3'
        @ok='handleOk3'
      />
      <a-modal v-model:open='open' title='设备详情' @ok='handleOpen'>
        {{ alarmsContentDetail }}
      </a-modal>
      <step-by-step-modal ref='modal' @ok='handleOk2' />
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'

import CreateItem from '@/views/device/modules/CreateForm.vue'
import CreateItem2 from '@/views/device/modules/CreateForm2.vue'
import {
  getDeviceList,
  createDevice,
  deleteDevice,
  updateDevice,
  getDeviceGroupList,
  createDeviceNew,
  GetDevice,
  createDeviceSetting, createDevicePushAll
} from '@/api/device'

import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
import CreateFormDevicelist from '@/views/device/modules/CreateFormDevicelist.vue'
import DeviceSetting from './modules/DeviceSetting'
import { create } from 'lodash'

const columns = [
  {
    title: 'ID',
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '设备编号',
    dataIndex: 'equipmentNo'
  },
  {
    title: '设备名称',
    dataIndex: 'alarmsName'
  },
  {
    title: '在线状态',
    dataIndex: 'onlineStatus',
    scopedSlots: { customRender: 'onlineStatus' }
  },
  {
    title: '采集时间',
    dataIndex: 'collectTime',
    sorter: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '200px',
    scopedSlots: { customRender: 'action' }
  }
]

const statusMap = {
  0: {
    text: '正常'
  },
  1: {
    text: '停用'
  }
}

export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    DeviceSetting,
    create,
    CreateItem2,
    StepByStepModal,
    CreateFormDevicelist,
    CreateItem
  },
  data() {

    this.columns = columns
    return {
      area: null,
      open: false,
      alarmsContentDetail: '',
      cityValue: '北京市/市辖区',
      id: 0,
      devicetitle: '',
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // create model
      visible2: false,
      confirmLoading2: false,
      mdl2: {
        equipmentNo: '',
        camera: '',
        charge: '',
        led: '',
        ledlum: '',
        lightLitlum: '',
        sw: '',
        swTime: ''
      },
      oldMd2: {},
      visible3: false,
      confirmLoading3: false,
      mdl3: {
        equipmentNo: ''
      },
      setting: {},
      mapEvent: {},
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {
        alarmsType: '光伏'
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        console.log('loadData request parameters:', requestParameters)
        return getDeviceList(requestParameters)
          .then(res => {
            const data = res.data
            data.list.forEach(element => {
              element.status = element.status == 0 ? '正常' : '停用'
              element.address = element.address == null ? '' : element.address
            })
            return data
          })
      },
      selectedRowKeys: [],
      selectedRows: [],
      groupList: []
    }
  },
  filters: {
    statusFilter(type) {
      return statusMap[type].text
    }
  },
  created() {
    this.getGroupList()
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    getGroupList() {
      var params = {
        pageNum: 1,
        pageSize: 100
      }
      getDeviceGroupList(params).then(res => {
        this.groupList = res.data.list
        console.log('groupList', this.groupList)
      })
    },
    handleDeleteOk(id) {
      var that = this
      this.$confirm({
        title: '确认要删除吗',
        onOk() {
          deleteDevice(id).then(res => {
            if (res.code == 200) {
              // 刷新表格
              that.$refs.table.refresh(true)
              that.$message.info('删除成功')
            } else {
              that.$message.error(res.message)
            }
          })
        },
        onCancel() {
        }
      })
    },
    handleAddVersion() {
      if (this.selectedRows.length > 1 || this.selectedRows.length == 0) {
        this.mdl3 = {
          equipmentNo: '',
          version: ''
        }
        this.visible3 = true
      } else {
        this.mdl3 = this.selectedRows[0]
        this.visible3 = true
      }
      console.log(' this.selectedRows ', this.selectedRows)
    },
    handleAdd() {
      this.mdl = {
        area: '/'
      }
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      record.area = '/'
      console.log('record', record)
      this.mdl = { ...record }
    },

    handleDetail(record) {
      this.open = true
      this.alarmsContentDetail = record.alarmsContentDetail
    },
    handleOpen() {
      this.open = false
    },

    handleDSettingOk(record) {
      console.log('record', record)
      this.devicetitle = '设置设备参数'
      // 将字符串'true' 'false'转换为布尔值
      for (let key in record) {
        if (record[key] == 'true') {
          record[key] = true
        } else if (record[key] == 'false') {
          record[key] = false
        }
      }
      this.mdl2 = record
      this.oldMd2 = JSON.parse(JSON.stringify(record))
      this.id = record.id
      this.visible2 = true
    },
    areaChange(area) {
      console.log('areaChange', area)
      this.mapEvent = area
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        // debugger
        if (!errors) {
          // values.address=this.mdl.address
          if (values.id > 0) {
            if (JSON.stringify(this.mapEvent) !== '{}') {
              values.province = this.mapEvent.regeocode.addressComponent.province
              values.city = this.mapEvent.regeocode.addressComponent.city
              values.longitude = this.mapEvent.position.lng
              values.latitude = this.mapEvent.position.lat
              values.address = this.mapEvent.address
            }
            this.confirmLoading = true
            updateDevice(values).then(res => {
              console.log('res', res)
              this.confirmLoading = false
              // 刷新表格
              this.$refs.table.refresh()
              if (res.code == 200) {
                // 重置表单数据
                this.visible = false
                form.resetFields()
                this.$message.info('修改成功')
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            // values.province = this.area[0]
            console.log('==================================', this.mapEvent)
            if (JSON.stringify(this.mapEvent) !== '{}') {
              values.province = this.mapEvent.regeocode.addressComponent.province
              values.city = this.mapEvent.regeocode.addressComponent.city
              values.longitude = this.mapEvent.position.lng
              values.latitude = this.mapEvent.position.lat
              values.address = this.mapEvent.address
            }
            // 新增
            this.confirmLoading = true
            createDevice(values).then(res => {
              console.log('res', res)
              this.confirmLoading = false
              // 刷新表格
              this.$refs.table.refresh()
              if (res.code == 200) {
                // 重置表单数据
                this.visible = false
                form.resetFields()
                this.$message.info('新增成功')
              } else {
                this.$message.error(res.message)
              }
            })
          }
        } else {
          this.confirmLoading = false
        }
      })
      form.resetFields()
    },
    handleCancel() {
      this.visible = false

      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleCancel2() {
      this.visible2 = false

      // const form = this.$refs.createModal.form
      // form.resetFields() // 清理表单数据（可不做）
    },
    handleCancel3() {
      this.visible3 = false

      // const form = this.$refs.createModal.form
      // form.resetFields() // 清理表单数据（可不做）
    },
    handleOk2(list) {
      const form = this.$refs.createItem.form
      this.confirmLoading2 = true
      const params = {
        equipmentNo: this.mdl2.equipmentNo,
        camera: this.mdl2.camera,
        charge: this.mdl2.charge,
        led: this.mdl2.led,
        ledlum: this.mdl2.ledlum,
        light: this.mdl2.light,
        lightLitlum: this.mdl2.lightLitlum,
        sw: this.mdl2.sw,
        swTime: this.mdl2.swTime,
        ledCloseTime: this.mdl2.ledCloseTime,
        ledOpenTime: this.mdl2.ledOpenTime,
        periodTimeFlag: String(this.mdl2.periodTimeFlag),
        fullVoltage: this.md2.fullVoltage,
        shutoffVoltage: this.md2.shutoffVoltage,
      }
      for (let key in params) {
        if (key !== 'equipmentNo') {
          // 判断是不是布尔类型 是就转成字符串再判断
          if (params[key] === this.oldMd2[key]) {
            delete params[key]
          }
        }
      }
      if (this.mdl2.periodTimeFlag) {
        params.periodTimeList = list
      }
      if (!params?.led) {
        delete params.ledlum
        delete params.lightLitlum
      }
      if(!params?.sw) {
        delete params.swTime
      }
      if(params.ledlum || params.lightLitlum) {
        params.led = this.mdl2.led
      }
      if (params?.swTime) {
        params.sw = this.mdl2.sw
      }
      this.confirmLoading2 = true
      createDeviceNew(params).then(k => {
        console.log('k', k)
        this.visible2 = false
        this.confirmLoading2 = false
        if (k.code == 200) {
          this.$message.info('修改成功')
        } else {
          this.$message.error(res.message)
        }
      })
      // })
    },
    handleOk3() {
      const form = this.$refs.createItem2.form
      this.confirmLoading3 = true
      const params = {
        version: this.mdl3.version
      }
      if (this.mdl3.all) {
        params.equipmentNo = 'ALL'
      } else {
        params.equipmentNoList = this.mdl3.equipmentNo.split(',')
      }
      this.confirmLoading3 = true
      createDevicePushAll(params).then(k => {
        console.log('k', k)
        this.visible3 = false
        this.confirmLoading3 = false
        if (k.code == 200) {
          this.$message.info('修改成功')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    resetSearchForm() {
      this.queryParam = {
        date: moment(new Date())
      }
    }
  }
}
</script>
